<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="addAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="saveAction">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { giftApi as requestApi } from '@/api/api'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag, ElImage } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()
const delId = ref('')
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async (params: any) => {
    const res = await requestApi.page({
      ...params,
      ...searchParams.value
    })
    console.log(res)
    return {
      list: (res.data.rows || []).map((el) => {
        return {
          ...el
        }
      }),
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    console.log(delId.value)
    const res = await requestApi.del(unref(delId))
    return !!res
  }
})

const { dataList, loading, total } = tableState
const { getList, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('active.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('active.name')
  },
  {
    field: 'image',
    label: t('active.image'),
    slots: {
      default: (data: any) => {
        return (
          <ElImage
            preview-src-list={[data.row.image]}
            initial-index={0}
            src={data.row.image}
            preview-teleported
          ></ElImage>
        )
      }
    }
  },
  {
    field: 'store_count',
    label: t('active.store_count')
  },
  {
    field: 'sale_count',
    label: t('active.sale_count')
  },
  {
    field: 'collect_count',
    label: t('active.collect_count')
  },
  {
    field: 'status',
    label: t('active.status'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
              {data.row.status === 1 ? t('active.on_sale') : t('userDemo.not_on_sale')}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'create_time',
    label: t('active.createTime')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 180,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => editAction(row)}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="danger" onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('active.name'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const editAction = (row: any) => {
  dialogTitle.value = t('exampleDemo.edit')
  currentRow.value = row
  dialogVisible.value = true
}

const addAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
}

const delData = async (row: any | null) => {
  console.log(row)
  delId.value = row.id
  console.log(delId.value)
  await delList()
}

const saveAction = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    requestApi.save(formData).then(() => {
      saveLoading.value = false
      dialogVisible.value = false
      getList()
    })
  }
}
</script>
